<template>
  <base-modal :width="modAlProps.width" :isVisible="props.isVisible" :title="modAlProps.title" :isCancleBtn="isCancleBtn"
    @handleCancle="handleCancle" class="site_modal">
    <template v-slot:body>
      <div class="historyBox">
        <div>
          <span class="importButton" v-for="(option, index) in buttons" @click="handleSearchs(option.value, +index)"
            :class="selectBtnIndex == index && selectBtnIndex != 0 && selectBtnIndex != buttons.length - 1 ? 'selectBtn ABborder' : (selectBtnIndex == index ? 'selectBtn' : '')">{{
              option.label
            }}</span>
          <!-- <a-range-picker show-time v-model:value="timeValue" :valueFormat="valueFormat" @change="changeTime" /> -->
          <date-range-picker v-model:value="timeValue" :valueFormat="valueFormat" :showTime="true"
            :disabledInfo="disabledInfo" @change="changeTime"></date-range-picker>
        </div>
        <div class="statistics">
          <div v-for="item in shuju" class="statisticssj">
            <span>{{ item.value }}</span>
            <br />
            <span>{{ item.label }}</span>
          </div>
        </div>
        <div class="series">
          <div>
            <div class="seriesTitle" style="margin-bottom:24px;">访问设备</div>
            <div id="accessRecordList" class="canvas"></div>
          </div>

          <div style="flex:1">
            <div class="series_title">
              <span class="seriesTitle" v-if="swit == 1">访问记录</span>
              <span class="seriesTitle" v-else>访问地域</span>
              <div class="swit">
                <a @click="switclick(1)" v-if="swit == 2"> 地图 </a>
                <a @click="switclick(2)" v-else> 表格 </a>
              </div>
            </div>
            <div id="visitAreaList" class="canvas1" v-if="swit == 1"></div>
            <div v-else style="margin-top: 24px">
              <treeTable :columns="columns.areaColumn" :dataSource="areaList" :isSelect="false" :scroll="scroll"
                ref="tagBaseTables" :isShowPagination="false" :rowSelection="1"></treeTable>
            </div>
          </div>
        </div>
      </div>
    </template>
  </base-modal>
</template>
<script lang="ts" setup>
import { ref, reactive, nextTick, onMounted, defineComponent, watch } from "vue";
import baseModal from "@/components/modal/baseModal.vue";
import treeTable from "@/components/table/baseTable.vue";
import { dataSourceType, detailDataItemType } from "@/type";
import request from "@/api/index";
import getters from "@/store/getters";
import { optionPie, optionArea } from "./echartType/options";
import { initEcharts } from "@/components/echarts/index";
import { scrollType } from "@/type.d";
import dateRangePicker from "@/components/picker/dateRangePicker.vue"
import columns from "@/components/table/tableConfig/tableColumn/contentManageColumn";
import china from "@/assets/china.json";
import * as echarts from "echarts";
import { cloneDeep } from "lodash";
//interface
interface Options {
  [propName: string | number]: any;
}
const props = defineProps({
  isVisible: {
    type: Boolean,
    default: false,
  },
  contentIds: {
    type: Array,
    default: [],
  },
});

//data
//模态框数据
const modAlProps = reactive<Options>({
  width: "XL",
  title: "浏览记录",
});
//树结构数据
const fieldNames = reactive<dataSourceType>({
  title: "channelName",
  key: "id",
});
const buttons = reactive<dataSourceType>([
  {
    label: "今日",
    value: 1,
  },
  {
    label: "本周",
    value: 2,
  },
  {
    label: "本月",
    value: 3,
  },
  {
    label: "累计",
    value: 4,
  },
]);
const selectBtnIndex = ref<number>(0);
const shuju = reactive<dataSourceType>([
  {
    label: "总访问量",
    value: 0,
  },
  {
    label: "总点赞数",
    value: 0,
  },
  {
    label: "总评论数",
    value: 0,
  },
]);
const logData = ref(JSON.parse(JSON.stringify(optionPie)));
const areaData = ref(JSON.parse(JSON.stringify(optionArea)));

let isCancleBtn = ref<Boolean>(false);
const formState = ref<dataSourceType>({});
//模态框button按钮个数和文案修改
const siteOptions = ref<dataSourceType[]>([]);
const userInfo = getters.userInfo();
const expandedKeys = ref<(string | number)[]>([]);
const autoExpandParent = ref<boolean>(true);
const timeValue = ref<(string | number)[]>([]);
const resData = ref<(string | number)[]>([]);
const areaList = ref<(string | number)[]>([]);
const params = ref<dataSourceType>({ contentId: props.contentIds });
const chinadata = ref<any>(cloneDeep(china));
const valueFormat = ref("YYYY-MM-DD HH:mm:ss");
let scroll: scrollType = reactive({ y: 240, isFixed: false });

const swit = ref<Number>(1);
const onExpand = (keys: string[]) => {
  expandedKeys.value = keys;
  autoExpandParent.value = false;
};
//日期组件
const disabledInfo = reactive({//日期禁选
  type: 2,
  startDays: 0,
});
//获取站点层级树列表
const fetchSiteTreeList = async () => {
  const data: {} = {
    // orgId: userInfo.orgId,
    userId: userInfo.userId,
    allPermissions: true,
  };
  siteOptions.value = await request.fetchContentSiteList(data);
  // fetchChannelChannelTree();
};
const changeTime = (data: any) => {
  params.value.statisticsTimeStart = data[0];
  params.value.statisticsTimeEnd = data[1];
  fetchContentVisitRecord();
};
const emits = defineEmits(["handleOk", "handleCancle"]);
const handleOk = () => {
  emits("handleOk");
};

const handleCancle = (e: MouseEvent) => {
  emits("handleCancle", e);
};
// 格局化日期：yyyy-MM-dd
const formatDate = (date: any) => {
  var myyear = date.getFullYear();
  var mymonth = date.getMonth() + 1;
  var myweekday = date.getDate();
  if (mymonth < 10) {
    mymonth = "0" + mymonth;
  }
  if (myweekday < 10) {
    myweekday = "0" + myweekday;
  }
  return myyear + "-" + mymonth + "-" + myweekday;
};
let Nowdate = new Date();
let nowYear = Nowdate.getFullYear(); // 当前年
let date1 = Nowdate.getDate(); // 当前日
let nowDayOfWeek = Nowdate.getDay(); // 今天本周的第几天
let nowMonth = Nowdate.getMonth(); // 当前月
let sfm1 = " 00:00:00";
let sfm2 = " 23:59:59";
const handleSearchs = (data: any, index: number) => {
  selectBtnIndex.value = index;
  let date = [];
  if (data === 1) {
    params.value.statisticsTimeStart = formatDate(new Date(nowYear, nowMonth, date1)) + sfm1;
    params.value.statisticsTimeEnd = formatDate(new Date(nowYear, nowMonth, date1)) + sfm2;

  } else if (data === 2) {
    params.value.statisticsTimeStart = formatDate(
      new Date(nowYear, nowMonth, date1 + 1 - nowDayOfWeek)
    ) + sfm1;
    params.value.statisticsTimeEnd = formatDate(new Date(nowYear, nowMonth, date1)) + sfm2;

  } else if (data === 3) {
    params.value.statisticsTimeStart = formatDate(new Date(nowYear, nowMonth, 1)) + sfm1;
    params.value.statisticsTimeEnd = formatDate(new Date(nowYear, nowMonth, date1)) + sfm2;

  } else if (data === 4) {
    timeValue.value = [];

  }
  nextTick(() => {
    fetchContentVisitRecord();
  })

};
const switclick = (e: any) => {
  swit.value = e;
  if (e == 1) {
    console.log("sss");
    nextTick(() => {
      initEcharts("visitAreaList", areaData.value);
    });
  }
};
const fetchContentVisitRecord = async () => {
  const data = await request.fetchContentVisitRecord(params.value);
  data.contentVisitRecordStatistics.map((item: any, index: any) => {
    if (item.type <= 3) {
      shuju[item.type - 1].value = item.totalCnt;
      logData.value.dataset.source[item.type][1] = item.pcCnt;
      logData.value.dataset.source[item.type][2] = item.mobileCnt;
    }
  });
  let list: dataSourceType[] = [];
  data.provinceVisitStatistics.forEach((item: any, index: any) => {
    chinadata.value.features.forEach((data: any) => {
      if (item.provinceCode == data.properties.adcode) {
        list.push({
          name: data.properties.name,
          value: item.viewCnt,
          likeCnt: item.likeCnt,
        });
      }
    });
  });

  resData.value = data.contentVisitRecordStatistics;
  areaData.value.series = [
    {
      type: "scatter",
      coordinateSystem: "geo", // 对应上方配置
    },
    {
      type: "map",
      geoIndex: 0,
      coordinateSystem: "geo",
      data: [],
    },
  ];
  areaData.value.series[1].data = list;
  areaData.value.formatter = function (a: dataSourceType, b: dataSourceType) {
    return `${a["name"]}</br>访问量: ${a.data ? a.data.value : 0}</br>点赞数: ${a.data ? a.data.likeCnt : 0
      }`;
  };

  areaList.value = data.provinceVisitStatistics;
  nextTick(() => {
    initEcharts("accessRecordList", logData.value);
    initEcharts("visitAreaList", areaData.value);
  });
};

//onmounted
onMounted(async () => {
  params.value.statisticsTimeStart = formatDate(new Date(nowYear, nowMonth, date1)) + sfm1;
  params.value.statisticsTimeEnd = formatDate(new Date(nowYear, nowMonth, date1)) + sfm2;
  fetchContentVisitRecord();
});
</script>

<style lang="scss" scoped>
.historyBox {
  .importButton {
    padding: 5px 16px;
    border: 1px solid #D9D9D9;
    border-right: none;
    cursor: pointer;
    box-sizing: border-box;
    width: 62px;
    display: inline-block;
  }

  .ABborder {
    position: relative;
    border-left-width: 0;


    &:after {
      content: '';
      width: 1px;
      height: 100%;
      background-color: var(--theme_button_active_bg_color, #1F6DED);
      position: absolute;
      left: 0;
      top: 0;
      z-index: 1;
    }

    &:before {
      content: '';
      width: 1px;
      height: 100%;
      background-color: var(--theme_button_active_bg_color, #1F6DED);
      position: absolute;
      right: 0;
      top: 0;
      z-index: 1;
    }
  }



  .importButton:nth-of-type(1) {
    border-radius: 2px 0 0 2px;
    border-right: 1px solid #D9D9D9;
  }

  .importButton:nth-of-type(2) {
    border-left: none;
  }

  .importButton:nth-last-of-type(1) {
    border-right: 1px solid #D9D9D9;
    border-radius: 0 2px 2px 0;
  }

  .selectBtn {
    border-color: var(--theme_button_active_bg_color, #1F6DED) !important;
    color: var(--theme_button_active_bg_color, #1F6DED) !important;
    background: var(--theme_menu-itme_select_bg_color, #edf7ff) !important;
    ;
  }

  .ant-picker {
    margin-left: 16px;
  }

  .statistics {
    margin: 24px 0;
    width: 952px;
    height: 82px;
    background: linear-gradient(180deg, #edf7ff 0%, rgba(237, 247, 255, 0.05) 100%);
    border-radius: 4px 4px 4px 4px;
    opacity: 1;
    display: flex;
    align-items: center;

    .statisticssj {
      width: 130px;
      text-align: center;
      border-right: 1px solid rgba(0, 0, 0, 0.06);

      span:first-child {
        font-size: 24px;
        font-family: LLNumbersOnly-Bold, LLNumbersOnly;
        font-weight: bold;
        color: rgba(0, 0, 0, 0.85);
        line-height: 24px;
      }

      span:last-child {
        font-size: 14px;
        font-family: PingFang SC-Regular, PingFang SC;
        font-weight: 400;
        color: rgba(0, 0, 0, 0.45);
        line-height: 14px;
      }
    }
  }

  .series {
    display: flex;

    .series_title {
      display: flex;
      justify-content: space-between;
    }


  }

  .seriesTitle {
    padding: 0 8px;
    font-size: 16px;
    font-family: PingFang SC-Medium, PingFang SC;
    font-weight: 500;
    color: rgba(0, 0, 0, 0.85);
    font-weight: bold;
    line-height: 16px;
    height: 16px;
    border-left: 3px solid #1f6ded;
  }

  // .a-scroll {
  //   height: calc(100% - 80px);
  //   overflow-y: auto;
  // }
  .canvas {
    width: 330px !important;
    height: 400px;
    overflow-y: auto;
  }

  .canvas1 {
    width: 580px !important;
    height: 400px;
    overflow-y: auto;
  }

  .swit {
    font-size: 14px;
    font-family: PingFang SC-Regular, PingFang SC;
    font-weight: 400;
    color: #1f6ded;
    line-height: 14px;
  }

  .ant-table-cell:nth-last-of-type(1) {
    text-align: left !important;
    margin-right: 16px;
  }
}
</style>
<style lang="scss">
.historyBox {
  .ant-table-cell:nth-last-of-type(1) {
    text-align: left !important;
    margin-right: 16px;
  }
}
</style>
